﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace QueryByServerDemo
{
    public static class SerializeHelper
    {

        private static void ProcessFilePath(string xmlPath, string directoryPath)
        {
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
                using (FileStream fsCreate = new FileStream(xmlPath, FileMode.CreateNew, FileAccess.Write))
                { }
            }
            else if (!File.Exists(xmlPath))
            {
                using (FileStream fsCreate = new FileStream(xmlPath, FileMode.CreateNew, FileAccess.Write))
                { }
            }
        }

        public static void XmlSerialize(string xmlPath, object o)
        {
            string directoryPath = Path.GetDirectoryName(xmlPath);
            ProcessFilePath(xmlPath, directoryPath);
            using (FileStream fsWrite = new FileStream(xmlPath, FileMode.Create, FileAccess.Write))
            {
                XmlSerializer xs = new XmlSerializer(o.GetType());
                xs.Serialize(fsWrite, o);
            }
        }

        public static object XmlDeSerialize(string xmlPath, object o)
        {
            try
            {
                if (JudgeConfigPathExist(xmlPath))
                {
                    string directoryPath = Path.GetDirectoryName(xmlPath);
                    ProcessFilePath(xmlPath, directoryPath);
                    using (FileStream fsRead = new FileStream(xmlPath, FileMode.Open, FileAccess.Read))
                    {
                        XmlSerializer xs = new XmlSerializer(o.GetType());
                        if (fsRead.Length == 0)
                            return null;
                        return xs.Deserialize(fsRead);
                    }
                }
                return null;
            }
            catch 
            {
                return null;
            }
        }
        private static bool JudgeConfigPathExist(string regexPath)
        {
            bool b = false;
            if (File.Exists(regexPath))
            {
                b = true;
            }
            return b;
        }

    }
}
